package soa.security.rs.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.NamingException;
import org.springframework.stereotype.Service;
import soa.security.domain.LdapTree;
import soa.security.domain.Organization;
import soa.security.exception.OrganizationException;
import soa.security.mgr.service.OrganizationMgrService;
import soa.security.mgr.service.TreeMgrService;
import soa.security.rs.OrganizationService;
import soa.security.web.export.LdapTreeJsonFormatExport;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author CreGu
 * @date 2016/3/29
 */
@Service
public class OrganizationRsServiceImpl implements OrganizationService {
    protected static final Logger log = LoggerFactory.getLogger(OrganizationRsServiceImpl.class);

    @Resource
    private OrganizationMgrService organizationMgrService;
    @Resource
    private TreeMgrService treeMgrService;

    @Override
    public Organization getOrganization(String organizationId) throws OrganizationException {
        try {

            List<Organization> list = organizationMgrService
                    .getOrganization(organizationId);

            if(list!=null&&list.size()>0)
                return list.get(0);

            return null;
        } catch (NamingException e) {
            throw new OrganizationException(OrganizationException.ERROR_LDAP, e);
        } catch (OrganizationException e) {
            throw e;
        } catch (Exception e) {
            if (log.isDebugEnabled())
                log.debug("其他错误", e);
            throw new OrganizationException(OrganizationException.ERROR_OTHER,
                    e);
        }
    }

    @Override
    public String allOrganization() throws OrganizationException {
        // TODO Auto-generated method stub
        try {
            List<LdapTree> trees = treeMgrService.organizationRsTree();
            LdapTreeJsonFormatExport content = new LdapTreeJsonFormatExport(trees);
            return content.toString();
        } catch (NamingException e) {
            throw new OrganizationException(OrganizationException.ERROR_LDAP, e);
        } catch (OrganizationException e) {
            throw e;
        } catch (Exception e) {
            if (log.isDebugEnabled())
                log.debug("其他错误", e);
            throw new OrganizationException(OrganizationException.ERROR_OTHER,
                    e);
        }
    }
}
